import { Component, OnInit, Injector, ViewChild, ElementRef } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { NzNotificationService } from 'ng-zorro-antd';
import { ServiceProxy, PathDTO, SiteDTO } from '@shared/service-proxy/service-proxies';
import { loadModules } from 'esri-loader';
import esri = __esri;
import {AppConsts} from "@shared/AppConsts";

@Component({
  selector: 'app-path-detail-modal',
  templateUrl: './path-detail-modal.component.html',
  styleUrls: ['./path-detail-modal.component.less']
})
export class PathDetailModalComponent extends AppComponentBase implements OnInit {
  isVisible: boolean = false;

  @ViewChild('mapViewNode') private mapViewEl: ElementRef;
  lng: number;
  lat: number;
  radius: number;
  geoJson: string = '';

  constructor(injector: Injector,
    private _service: ServiceProxy,
    ) {
    super(injector);
  }

  ngOnInit() {

  }

  async initializeMap() {
    try {
      const [
        Map,
        MapView,
        ScaleBar,
        TileLayer,
        Graphic,
        GraphicsLayer] = await loadModules([
          'esri/Map',
          'esri/views/MapView',
          'esri/widgets/ScaleBar',
          'esri/layers/TileLayer',
          "esri/Graphic",
          "esri/layers/GraphicsLayer",
          'dojo/domReady!'
        ], {
        url: AppConsts.arcgisMapUrl,         css: AppConsts.arcgisStyleUrl
      });

      // const transJson = Graphic.fromJSON(JSON.parse(_that.selectedPath));
      // First create a point geometry (this is the location of the Titanic)
      const points = {
        type: "multipoint", // autocasts as new Point()
        points: [[
          this.start.lng, this.start.lat],
        [this.end.lng, this.end.lat]]
      };

      // Create a symbol for drawing the point
      const markerSymbol = {
        type: "picture-marker",  // autocasts as new PictureMarkerSymbol()
        url: "/assets/images/icon-flag.png",
        width: "24px",
        height: "24px",
        xoffset: "9px",
        yoffset: "10px"
      };
      // Create a graphic and add the geometry and symbol to it
      const pointGraphic = new Graphic({
        geometry: points,
        symbol: markerSymbol
      });


      const tempGraphicsLayer = new GraphicsLayer();
      const layer = new TileLayer({
        url: AppConsts.arcgisMapServerUrl
      });
      // Set type of map
      const map: esri.Map = new Map({
        // basemap: this._basemap,
        layers: [layer, tempGraphicsLayer]
      });

      const mapView: esri.MapView = new MapView({
        container: this.mapViewEl.nativeElement,
        center: this._center,
        zoom: this._zoom,
        map: map
      });

      // All resources in the MapView and the map have loaded.
      // Now execute additional processes
      mapView.when(() => {
        const scaleBar = new ScaleBar({
          view: mapView,
          unit: "dual" // The scale bar displays both metric and non-metric units.
        });
        mapView.ui.add(scaleBar, "bottom-left");

        if(this.geoJson){
          const transJson = Graphic.fromJSON(JSON.parse(this.geoJson));
          // tempGraphicsLayer.add(transJson);
          tempGraphicsLayer.addMany([pointGraphic, transJson]);
        }
        else{
          this.notification.error(this.l('notification_erro'), this.l('map_data_error'));
        }
      });


    } catch (error) {
      console.log('We have an error: ' + error);
    }

  }
  sites: SiteDTO[] = [];
  start: SiteDTO;
  end: SiteDTO;
  getSites(path: PathDTO) {
    this._service.getAllSitesUsingGET().subscribe(result => {
      this.sites = result.result.fieldList;
      this.start = this.sites.find(m => m.id == path.startSiteId);
      this.end = this.sites.find(m => m.id == path.endSiteId);
      this.initializeMap();
    })
  }

  show(path: PathDTO, lat: number, lng: number): void {
    this._center = [lng, lat];
    this.geoJson = path.geoJson;
    this.isVisible = true;

    debugger;
    this.getSites(path);
  }


  close() {
    this.isVisible = false;
  }
}
